﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.IO;
using System.Collections.Concurrent;
using ServerFramework.Tools;

namespace Development.Tools
{
    /// <summary>
    /// 数据表管理类
    /// </summary>
    public class TableManager
    {

        private static TableManager _instance;
        public static TableManager Instance { get { if (_instance == null)_instance = new TableManager(); return _instance; } }

        private Dictionary<string, DataFormBase> _tables = new Dictionary<string, DataFormBase>();
        private FileSystemWatcher _fileWatcher = null;


        /// <summary>
        /// 初始化
        /// </summary>
        public void Init()
        {
            if (!Directory.Exists("tables/"))
            {
                Directory.CreateDirectory("tables/");
            }
            var types = Assembly.GetEntryAssembly().GetTypes();
            var baseType = typeof(DataForm<>);
            foreach (var ty in types)
            {
                if (ty.BaseType != null)
                {
                    if (ty.BaseType.Name == baseType.Name)
                    {
                        DataFormBase table = GlobalDefine.CreateObject(ty) as DataFormBase;
                        if (table.Load(ty.Name.Replace("Table", "Template") + ".xml"))
                        {
                            _tables.Add(ty.Name.Replace("Table", ""), table);
                        }
                        else
                        {
                            Log.WriteLog(ELogLevel.LOG_ERROR, "load " + ty.Name + " fail");
                        }
                    }
                }
            }
            AddFileWatcher("tables/", "*.xml");
        }

        private void AddFileWatcher(string path,string filter)
        {
            if (_fileWatcher == null)
            {
                _fileWatcher = new FileSystemWatcher(path, filter);
                _fileWatcher.Changed += watcher_Changed;
                _fileWatcher.EnableRaisingEvents = true;
            }
        }

        void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            try
            {
                string tableName = e.Name.Replace("Template.xml", "");
                DataFormBase table = null;
                if (_tables.TryGetValue(tableName, out table))
                {
                    table.Load(e.Name);
                    Log.WriteLog(ELogLevel.LOG_INFO, "reload " + e.Name + " success");
                }
            }
            catch(Exception ex)
            {
                Log.WriteLog(ELogLevel.LOG_INFO, ex.Message);
            }
           
        }

       



        public T Get<T>(int id) where T : BaseData
        {
            string tableName = typeof(T).Name.Replace("Template", "");
            if(_tables.ContainsKey(tableName))
            {
                return _tables[tableName].GetData(id) as T;
            }
            return null;
        }

        public T Get<T>(Predicate<T>　match) where T : BaseData
        {
            T t = null;
            T[] table = GetTable<T>();
            foreach(var x in table)
            {
                if(match(x))
                {
                    t = x;
                    break;
                }
            }
            return t;
        }

        public T [] GetTable<T>() where T : BaseData
        {
            string tableName = typeof(T).Name.Replace("Template", "");
            if (_tables.ContainsKey(tableName))
            {
                return _tables[tableName].GetTable<T>();
            }
            return null;
        }

      
    }
}
